<template>
	<!-- 新增课程 -->
	<div style="height: 100%; width: 100%;">
		<div v-show="showImgFlag"
			style="width: 100%;height: 150%;position: absolute;z-index: 2021;background: rgba(0, 0, 0, 0.3);">
			<img style="width: 100%;height: 100%;" :src="localId">
			<button @click="saveImg" class="btn">确定选择</button>
			<button @click="showImgFlag =!showImgFlag" class="btn"
				style="background-color: gray;color: white;">取消</button>
		</div>
		<div class="weui-cell">
			<button class="backBtn" @click="goBack">返回</button>
		</div>
		<!-- 		<div v-show="showImgFlag">
			<img :src="localId">
			<button class="btn">确定选择</button>
			<button class="btn">取消</button>
		</div> -->


		<div class="weui-cells__group weui-cells__group_form">
			<div class="weui-cells__title" style="margin-top: 0.625rem;">课程信息</div>
			<div class="weui-cells weui-cells_form">
				<div class="weui-cell weui-cell_active">
					<div class="weui-cell__hd"><label class="weui-label">课程名</label></div>
					<div class="weui-cell__bd">
						<input id="js_input" v-model="caseInfo.name" class="weui-input" placeholder="填写课程名">
					</div>
				</div>
				<div class="weui-cell weui-cell_active">
					<div class="weui-cell__hd"><label class="weui-label">课程类型</label></div>
					<div class="weui-cell__bd">
						<select v-model="caseInfo.caseType" class="weui-select">
							<option v-for="item in caseTypes" :key="item.caseType" :label="item.caseTypeName" :value="item.caseType">
							</option>
						</select>
					</div>
				</div>
				<div class="weui-cell weui-cell_active">
					<div class="weui-cell__hd"><label class="weui-label">课程描述</label></div>
					<div class="weui-cell__bd">
						<textarea class="weui-textarea" v-model="caseInfo.desc" placeholder="填写填写课程描述"></textarea>
					</div>
				</div>
				<div class="weui-cell weui-cell_active">
					<div class="weui-cell__hd"><label class="weui-label">学习目标</label></div>
					<div class="weui-cell__bd">
						<textarea class="weui-textarea" v-model="caseInfo.caseDist" placeholder="填写填写课程描述"></textarea>
					</div>
				</div>
				<div class="weui-cell weui-cell_active">
					<div class="weui-cell__hd"><label class="weui-label">适合人群</label></div>
					<div class="weui-cell__bd">
						<textarea class="weui-textarea" v-model="caseInfo.casePeople" placeholder="填写填写课程描述"></textarea>
					</div>
				</div>
				<div class="weui-cell weui-cell_active">
					<div class="weui-cell__bd ">
						<span class=" fl">课程图片</span>
					</div>
					<div class="weui-cell__hd" style="width: 20%;">
						<button style="width: 60%;font-size: 12px;padding: 5px;color: black;" @click="toUpload"
							v-model="caseInfo.imgPath" class="weui-btn">选择图片</button>
					</div>
					<div class="weui-cell__ft " style="width: 20%;">
						<img @click="showImg" style="width: 100%;height: 100%;" :src="localId">
					</div>
				</div>
				<!-- <div class="weui-cell weui-cell_active">
					<div class="weui-cell__hd"><label class="weui-label">课程售价</label></div>
					<div class="weui-cell__bd">
						<input type="number" v-model="caseInfo.caseSale" class="weui-input" value="售价" />
					</div>
				</div>
				<div class="weui-cell weui-cell_active">
					<div class="weui-cell__hd"><label class="weui-label">课程优惠价</label></div>
					<div class="weui-cell__bd">
						<input type="number" v-model="caseInfo.caseSaleDz" class="weui-input" value="售价" />
					</div>
				</div> -->
				<div class="weui-cell weui-cell_active weui-cell_switch">
					<div class="weui-cell__bd">是否启用课程</div>
					<div class="weui-cell__ft">
						<label for="switchCP" class="weui-switch-cp">
							<input id="switchCP" class="weui-switch-cp__input" v-model="caseInfo.status" type="checkbox"
								checked="checked">
							<div class="weui-switch-cp__box"></div>
						</label>
					</div>
				</div>

				<div>
					<button @click="addCase" class="btn">保存</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import uwLoadJs from '@/utils/uwLoad'
	import constant from '@/utils/constant'
	import apis from '@/utils/apis'
	import {
		getToken
	} from '@/utils/auth'
	import {
		createJsapiSignature,
		downloadImgFronWx,
	} from '@/apis/wx/weixinJs.js'
	import {
		saveCase,getCaseTyeList
	} from '@/apis/tech/tech.js'
	import {
		isAndroid
	} from '@/utils/utils' //引入
	import configs from '@/utils/config.js' //引入
	import{showMsg} from '@/apis/common/common.js'
	export default {
		inject: ['reload'],
		data() {
			return {
				caseTypes:[],
				thisPath: '', //当前页面路径
				localId: null, // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片\
				caseInfo: {
					name: '',
					desc: '',
					imgPath: '',
					caseDist: '',
					casePeople: '',
					caseType: '1', //类型默认1，瑜伽
					status: false,
				},
				serverId: "", //发送到后端用来请求微信图片缓存到本地
				showImgFlag: false,
			}
		},
		created() {
			debugger
			this.thisPath = this.$router.history.current.path;
			this.getTicker();
		},
		mounted() {
			this.getCaseTypeList();
		},
		methods: {
			async getCaseTypeList(){
			  await	getCaseTyeList(apis.getCaseTyeList).then( res => this.caseTypes = res.data);
			},
			saveImg() {
				this.$showLoading({
					showLoadingToastFlag: true,
				});
				this.showImgFlag = !this.showImgFlag
				//此处请求后端保存图片
				downloadImgFronWx(apis.downloadImgFronWx, {
					"medical_id": this.serverId
				}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
						this.caseInfo.imgPath = configs.FILEBASEURL + res.resultMsg;
						showMsg(this,"上传成功！", null, "success");
					} else {
						showMsg(this,"上传失败，请稍后重试！");
						this.localId = "";
					}
					this.$hideLoading();
				}).catch(err => {
					this.$hideLoading();
				});
			},
			addCase() {
				this.$showLoading({
					showLoadingToastFlag: true,
				});
				saveCase(apis.saveCase, this.caseInfo).then(res => {
					if (res.resultCode == constant.SUCCESS) {
						showMsg(this,res.resultMsg,null, "success")
					} else {
						showMsg(this,res.resultMsg,null, "danger")
					}
					this.$hideLoading();
					this.$router.go(-1);
				}).catch(err => {
					this.$hideLoading();
				})
			},

			showImg() {
				this.showImgFlag = true;
			},
			//获取微信权限
			getTicker() {
				this.$showLoading({
					showLoadingToastFlag: true,
				});
				let that = this;
				let fullUrl = constant.PROJECTPATH + this.thisPath;
				let url = "";
				console.log("getTicker url1" + window.location.href.split('#')[0])
				console.log("window.__wxjs_is_wkwebview: " + window.__wxjs_is_wkwebview)
				console.log("fullUrl: " + fullUrl)
				if (window.__wxjs_is_wkwebview === true) {
					url = fullUrl.split('#')[0]
				} else {
					url = window.location.href.split('#')[0]
				}
				console.log("getTicker url2" + url)
				url = encodeURIComponent(url);
				debugger
				console.log("getTicker ur3" + url)
				createJsapiSignature(apis.createJsapiSignature + "?url=" + url).then(res => {
					if (res.resultCode == constant.SUCCESS && res.data != null) {
						let jsapiSignature = res.data;
						console.log("jsapiSignature:" + JSON.stringify(jsapiSignature))
						this.$wx.config({
							debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							appId: jsapiSignature.appId, // 必填，公众号的唯一标识
							timestamp: jsapiSignature.timestamp, // 必填，生成签名的时间戳
							nonceStr: jsapiSignature.nonceStr, // 必填，生成签名的随机串
							signature: jsapiSignature.signature, // 必填，签名
							jsApiList: ['chooseImage', 'uploadImage', 'getLocalImgData',
								'downloadImage'
							] // 必填，需要使用的JS接口列表
						});

					}
					this.$hideLoading();
				}).catch(err => {
					that.$toast({
						text: "选择图片初始化失败 请刷新重试!",
						type: 'warning',
						duration: 1000
					})
					this.$hideLoading();
				})
			},

			goBack() {
				this.$router.go(-1);
			},
			toUpload() {
				const that = this;
				return new Promise((resolve, reject) => {
					that.$wx.chooseImage({
						count: 1, // 默认9
						sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
						success: function(res) {
							// self.localIds = res.localIds
							console.log(res, '--------------------')
							that.syncUpload(res.localIds, 0)
						},
						cancel: function(res) {
							console.log('---------chooseImage:cancel----')
							console.log(res)
							resolve({
								image: res.errMsg
							})
						},
						fail: function(res) {
							console.log('---------chooseImage:faild----')
							console.log(res)
							reject({
								message: res.errMsg
							})
						}
					})
				})
			},
			async syncUpload(localIds, index) {
				const self = this
				console.log('异步请求syncUpload')
				self.$wx.uploadImage({
					localId: localIds[index],
					isShowProgressTips: 1, // 默认为1，显示进度提示
					success: async res => {
						self.serverId = res.serverId; // 返回图片的服务器端ID
						console.log("serverId:" + self.serverId);
						self.syncDownload(self.serverId);
					}
				})
			},
			async syncDownload(serverId) {
				const self = this
				console.log('异步请求syncDownload')
				self.$wx.downloadImage({
					serverId: serverId, // 需要下载的图片的服务器端ID，由uploadImage接口获得
					isShowProgressTips: 1, // 默认为1，显示进度提示
					success: function(res) {
						var localId = res.localId; // 返回图片下载后的本地ID
						console.log("download localId:" + localId);
						if (isAndroid()) {
							self.localId = localId;
						} else {
							self.getLocalImgData(localId);
						}
					},
					fail: function(res) {
						console.log('-------------syncDownload:faild----')
						console.log(res)
						reject({
							message: res.errMsg
						})
					}
				});
			},
			//苹果需要下载到本地才能在页面上看
			async getLocalImgData(localId) {
				const self = this
				console.log('异步请求getLocalImgData')
				self.$wx.getLocalImgData({
					localId: localId, // 图片的localID
					success: function(res) {
						var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
						localData = localData.replace('jgp',
							'jpeg'); //iOS 系统里面得到的数据，类型为 image/jgp,因此需要替换一下  
						self.localId = localData;
					}
				});
			},

		},
		destroyed() {
			console.log("destory" + window.entryUrl)
			localStorage.removeItem(window.entryUrl);
		}
	}
</script>

<style>
	@import "../../assets/css/returnBtn.css";

	.backBtn {
		width: 3.125rem;
		display: block;
		text-align: center;
		line-height: 100%;
		padding: 0.3em;
		font: 16px Arial, sans-serif bold;
		font-style: normal;
		text-decoration: none;
		margin: 2px;
		vertical-align: text-bottom;
		zoom: 1;
		outline: none;
		font-size-adjust: none;
		font-stretch: normal;
		border-radius: 50px;
		box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
		text-shadow: 0px 1px 1px rgba(0, 0, 0, 0.3);
		color: #fefee9;
		border: 0.2px solid #2299ff;
		background-repeat: repeat;
		background-size: auto;
		background-origin: padding-box;
		background-clip: padding-box;
		background-color: #3399ff;
		background: linear-gradient(to bottom, #eeeff9 0%, #3399ff 100%);
	}
</style>
